// pages/product/unit-list/unit-list.js
import ProductService from "../../../class/service/ProductService";
import SmsService from "../../../class/service/SmsService";
import MallService from "../../../class/service/MallService";
import Router from "../../../class/Router";
import Tips from "../../../utils/Tips";

const util = require("../../../utils/util.js")
const storage = require("../../../utils/storage.js")
const constant = require("../../../constant.js")
const notification = require("../../../utils/WxNotificationCenter.js");

const productService = new ProductService();
const smsService = new SmsService();
const mallService = new MallService();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    init: false,
    needMobile: false,
    showDialog: false,
    codeMsg: '获取验证码'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var that = this;
    that.setData({ courseId: options.id })

    var unionid = wx.getStorageSync(storage.keys.unionid);
    that.setData({
      unionid: unionid
    })

    var openid = wx.getStorageSync(storage.keys.openid);
    that.setData({
      openid: openid
    })

    var mobile = wx.getStorageSync(storage.keys.mobile);
    that.setData({
      mobile: mobile
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;

    if (that.data.mobile) {
      that.initData()
    } else {
      that.setData({
        init: false,
        needMobile: true
      })
    }
    

  },

  initData: function () {
    var that = this;
    Tips.loading();
    productService.detail(that.data.courseId, that.data.unionid).then(data => {
      Tips.loaded();
      that.setData({
        "init": true,
        "hasCourse": data.hasCourse,
        "course": data.course,
        "courseUnits": data.courseUnits,
        "courseMaterial": data.materails,
        "img": data.img,
        "message1": data.messsage1,
        "message2": data.message2,
      })
    }, res => {
      Tips.error("获取练习失败");
      that.setData({
        "init": true
      })
    })
  },

  goUnitdetail: function (e) {
    wx.navigateTo({
      url: '../../../pages/product/unit-detail/unit-detail?id=' + e.currentTarget.dataset.id + '&productId=' + this.data.courseId,
    })
  },

  previewPdf: function (e) {
    const downloadTask = wx.downloadFile({
      url: e.currentTarget.dataset.pdf, //仅为示例，并非真实的资源
      success: function (res) {
        console.log(res);
        var filePath = res.tempFilePath
        wx.openDocument({
          filePath: filePath,
          success: function (res) {
            console.log('打开文档成功')
          },
          fail: function (res) {
            console.log(res)
          }
        })
      }
    })

    downloadTask.onProgressUpdate((res) => {
      wx.showLoading({
        title: '加载中...' + res.progress + '%',
      })
      if (res.progress === 100) {
        wx.hideLoading()
      }
    })
  },

onInputPhone: function (e) {
  var that = this;
  that.setData({
    phone: e.detail
  })
},

openMinima: function (e) {
  console.log("open now")
  this.setData({
    showDialog: true
  })
},

inputCode: function (e) {
  var that = this;
  that.setData({
    code: e.detail
  })
  if (that.data.code.length == 6) {
    that.bindUser();
  }
},

bindUser: function () {
  var that = this;

  smsService.bindUser(that.data.unionid, that.data.phone, that.data.code, that.data.token, that.data.openid).then(data => {
    that.setData({
      mobile: data.user.mobile
    })
    wx.setStorageSync(storage.keys.mobile, that.data.mobile)
    that.setData({
      init: false,
      needMobile: false
    })
    that.initData();
  }, res => {
    Tips.error("绑定验证码失败");
    that.setData({
      disableGetCode: false,
      codeMsg: "获取验证码"
    })
  })
},

validMobile: function () {
  var that = this;
  if (!that.data.phone) {
    that.showMessage("请先输入手机")
    return false;
  } else if (!/^((13)|(14)|(15)|(16)|(17)|(18)|(19))\d{9}$/.test(that.data.phone)) {
    that.showMessage("请输入正确的手机")
    return false;
  }

  return true;
},

onSendSms: function (event) {

  var that = this;
  if (that.validMobile()) {

    that.setData({
      disableGetCode: true
    })

    var seconds = 60;
    var interval = setInterval(function (e) {
      seconds--;
      if (seconds < 0) {
        that.setData({
          disableGetCode: false,
          codeMsg: "重新获取验证码"
        })
        clearInterval(interval);
      } else {
        that.setData({
          codeMsg: "发送中（" + seconds + "）秒"
        })
      }
    }, 1000)

    smsService.send(that.data.phone).then(data => {
      that.setData({
        token: data.token
      })
      Tips.loaded();
    }, res => {
      Tips.error("获取验证码失败");
      that.setData({
        disableGetCode: false,
        codeMsg: "获取验证码"
      })
      clearInterval(interval);
    });
  }
},

showMessage: function (text) {
  var that = this
  that.setData({
    showMessage: true,
    messageContent: text
  })
  setTimeout(function () {
    that.setData({
      showMessage: false,
      messageContent: ''
    })
  }, 3000)
},

/**
 * 生命周期函数--监听页面隐藏
 */
onHide: function () {

},

/**
 * 生命周期函数--监听页面卸载
 */
onUnload: function () {

},

/**
 * 页面相关事件处理函数--监听用户下拉动作
 */
onPullDownRefresh: function () {

},

/**
 * 页面上拉触底事件的处理函数
 */
onReachBottom: function () {

},

/**
 * 用户点击右上角分享
 */
onShareAppMessage: function () {

}
})